package com.jwaoo.mobile.common.crash;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Environment;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;
import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.reflect.Field;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by jwaoo on 2017/6/20.
 */

public class CrashHandler implements Thread.UncaughtExceptionHandler {
    public static final String TAG = "CrashHandler";

    public static ICrashHandlerLisener callBackLisener;

    // CrashHandler 实例
    private static CrashHandler INSTANCE = new CrashHandler();

    // 程序? Context 对象
    private Context mContext;

    // 系统默认 UncaughtException 处理?
    private Thread.UncaughtExceptionHandler mDefaultHandler;

    private CrashHandler() {
    }

    /**
     * 获取CrashHandler 实例
     */
    public static CrashHandler getInstance() {
        return INSTANCE;
    }

    /**
     * 初始
     *
     * @param context
     */
    public void init(Context context,ICrashHandlerLisener mCallBackLisener) {
        mContext = context;
        callBackLisener = mCallBackLisener;
        // 获取系统默认 UncaughtException 处理?
        mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();

        // 设置CrashHandler 位程序的默认处理?
        Thread.setDefaultUncaughtExceptionHandler(this);
    }


    /**
     * 当UncaughtException 发生时会传入该函数来处理
     */
    @Override
    public void uncaughtException(Thread thread, Throwable ex) {
        if (!handleException(ex) && mDefaultHandler != null) {
            // 如果用户没有处理，则让系统默认的异常处理器来处理
            ex.printStackTrace();
            mDefaultHandler.uncaughtException(thread, ex);
        }
        ex.printStackTrace();
    }

    /**
     * 自定义错误处理，收集错误信息，发送错误报告等操作
     *
     * @param ex
     * @return true 如果处理了该异常信息；否则返回false
     */
    private boolean handleException(Throwable ex) {
        if (ex == null) {
            return false;
        }
        ex.printStackTrace();
        callBackLisener.crashHanderCallBack(mContext,ex);
        return true;
    }

    public interface ICrashHandlerLisener {
        /**
         * app闪退回调处理方法
         * @param context
         */
        public void crashHanderCallBack(Context context ,Throwable ex);
    }

    public String getStackTrace(Throwable throwable){
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw, true);
        throwable.printStackTrace(pw);
        return sw.getBuffer().toString();
    }
}